package com.cctc.juc.demo.Bitc.Ammap.GThreadLocal.AThreadLocal;

import lombok.Data;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class AThreadLocalDemo {
    @Data
    private static class Foo {
        private static final AtomicInteger ID = new AtomicInteger(0);
        private int index = 0;
        private int data = 10;

        public Foo() {
            index = ID.getAndIncrement();
        }

        @Override
        public String toString() {
            return index + "@Foo{data=" + data + "}";
        }
    }

    private static final ThreadLocal<Foo> THREAD_LOCAL = ThreadLocal.withInitial(() -> new Foo());

    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            final int index = i;
            new Thread(() -> {
                System.out.printf("当前线程名称：%s，线程本地变量为：%s -> %s%n",
                                  Thread.currentThread().getName(),
                                  THREAD_LOCAL.get(),
                                  "ThreadLocal 应用场景：线程隔离 & 跨函数数据传递。");

                Foo foo = THREAD_LOCAL.get();
                foo.setData(foo.getData() + index);
                THREAD_LOCAL.set(foo);

                System.out.printf("当前线程名称：%s，更新后的线程本地变量为：%s%n",
                                  Thread.currentThread().getName(),
                                  THREAD_LOCAL.get());
            }).start();

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
